'use strict';

var vkmail;
try {
    vkmail = require('vk-mail');
} catch (err) {
    console.error("请先添加公共模块：vk-mail");
}

exports.main = async (event, context) => {
    let res = { code: 0, msg: "" ,data:""};

    let {
        email, // 前端接收邮箱
        type = "bind", // 前端接收验证码类型（如: login register bind unbind）
    } = event;
	
    let emailConfig = {
        "host": "smtp.qq.com",
        "port": 465,
        "secure": true,
        "auth": {
            "user": "339851531@qq.com", // 发件人邮箱账号
            "pass": "htmxdhduznhibiib", // 账号授权码
        }
    };

    if (!email) return { code: 400, msg: "邮箱不能为空" };

    let code = Math.floor(Math.random() * 9000) + 1000;
    let text = `邮箱${email}的注册验证码是： ${code}，打死也不要告诉别人！`;

    // 创建邮箱服务实例
    let emailService = vkmail.createTransport({
        "host": emailConfig.host,
        "port": emailConfig.port,
        "secure": emailConfig.secure, // use SSL
        "auth": emailConfig.auth
    });

    try {
        // 发送邮件
        res.sendMailRes = await emailService.sendMail({
            "from": emailConfig.auth.user, // 邮件的发送者
            "to": email, // 邮件的接收者
            "cc": emailConfig.auth.user, // 由于邮件可能会被当成垃圾邮件，但只要把右键抄送给自己一份，就不会被当成垃圾邮件。
            "subject": "小二云盘官方邮件", // 邮件的标题
            "text": text, // 邮件的内容
        });
        // 标记发送成功
        res.code = 200;
        res.msg = "发送成功";
		res.data =code.toString()
    } catch (err) {
        res.code = 400;
        res.msg = "邮件发送失败";
        res.err = err;
    }
    return res;
};